package markor.jpa.hello.jpa.controller;

import markor.jpa.hello.jpa.bean.User;
import markor.jpa.hello.jpa.exception.CommonBizException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

@RestController
public class HaController {

    @RequestMapping("hello")
    public String hello(@Valid User user) {

        String success = "success";
        return success;
    }

    @RequestMapping("hi")
    public String hi(@Valid @RequestBody User user) {
        String success = "error";
        return success;
    }

    @RequestMapping("")
    public User ha() {
        User user = new User();
        user.setUsername("caichangmeng");
        user.setPassword("password");
        user.setAge(27);
        user.setId(12);
        return user;
    }

    @RequestMapping("err")
    public void a() {
        throw new CommonBizException("1002","参数异常");
    }

    @RequestMapping("redirect")
    public String haha(@RequestParam(name = "openId", required = false) String openId,
                       @RequestParam(name = "status", required= false) String status,
                       HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        System.out.println(uri);
        if (openId == null || openId.trim().equals("")) {
            if ("2".equals(status)) {
                return "stop";
            }
            request.getRequestDispatcher("/receive?status = 1&uri="+uri).forward(request,response);
            return uri;
        }
        return openId;
    }

    @RequestMapping("receive")
    public String zeze(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam(name = "status",required = false)String status, String uri) throws ServletException, IOException {
        String openId = "openId";
        // request.getRequestDispatcher(uri+"?openId="+openId+"&status=2").forward(request,response);
        response.sendRedirect(uri+"?openId="+openId);
        return null;
    }
}
